package pl.edu.pk.cc.server.main;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jboss.logging.Logger;

import pl.edu.pk.cc.common.util.CCServerRequest;
import pl.edu.pk.cc.server.hibernate.CCHibernateUtil;

/**
 * Servlet implementation class CCMainServlet
 */
public class CCMainServlet extends HttpServlet {

	private static Logger logg = Logger.getLogger(CCMainServlet.class);
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		try (PrintWriter writer = response.getWriter()) {
			writer.write("<!DOCTYPE html><html><head><title>CCServlet</title></head><body><h1>Call Center Server is up!</h1></body?</html>");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("application/x-java-serialized-object");
		CCServerRequest clientRequest = null;
		try (ObjectInputStream in = new ObjectInputStream(request.getInputStream())) {
			clientRequest = (CCServerRequest) in.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (clientRequest != null) {
			logg.info("Server called by session " + clientRequest.getSessionID());
			Object serverResponse = CCServletRequestInterpreter.process(clientRequest);
			try (ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream())) {
				oos.writeObject(serverResponse);
				oos.flush();
			} catch (Exception e) {
				e.printStackTrace();
			}
			logg.info("Server responded to " + clientRequest.getSessionID());
		} else {
			logg.warn("Emtpy client request!");
		}

	}

	@Override
	public void init() throws ServletException {
		super.init();
		CCServerSessionsManager.init();
		CCHibernateUtil.getSessionFactory().getCurrentSession();
		logg.info("Server initialized properly!");
	}

}
